<template>
    <div>
        <el-breadcrumb>
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">权限管理</a></el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">角色列表</a></el-breadcrumb-item>
        </el-breadcrumb>
        
        <el-card>
            <el-row>
                <el-col>
                    <el-button type="primary" @click="showAddDialog">添加角色</el-button>
                </el-col>
            </el-row>
            <!-- 添加角色对话框 -->
            <el-dialog
                title="添加角色"
                :visible.sync="showAddDialogVisible"
                width="30%"
                >
                <el-form :model="addRolesForm" :rules="RolesRules" ref="addRolesRef"  label-width="180px">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="addRolesForm.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="addRolesForm.roleDesc"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="showAddDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addRoles">确 定</el-button>
                </span>
             </el-dialog>
            <!-- 角色列表按区域 -->
            <el-row>
            <el-table :data="rolesList" border stripe>
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row 
                        v-for="(item1,i1) in scope.row.children" 
                        :class="['bdbottom',i1===0?'bdtop' : '','vcenter']"
                        :key="item1.id">
                            <!-- 渲染一级权限 -->
                            
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row,item1.id)">
                                    {{item1.authName}}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col >
                            <!-- 渲染二三级权限 -->
                            <el-col :span="19">
                                <!-- 二级权限 -->
                                <el-row 
                                v-for="(item2,i2) in item1.children" 
                                :class="[i2 === 0 ? '' : 'bdtop','vcenter']"
                                :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag 
                                        type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <!-- 三级权限 -->
                                        <el-row 
                                        v-for="(item3,i3) in item2.children" 
                                        :class="[i3 === 0 ? '' : 'bdtop']"
                                        :key="item3.id">
                                            <el-tag 
                                            type="warning" closable
                                            @close="removeRightById(scope.row,item3.id)"
                                            >{{item2.authName}}</el-tag>
                                        </el-row>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>

                    </template>
                </el-table-column>
                <el-table-column type="index">#</el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
                        <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteRoles(scope.row.id)"></el-button>
                        <el-button type="warning" size="mini" icon="el-icon-s-tools" @click="showSetRightDialog(scope.row)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            </el-row>
        </el-card>
        <!-- 编辑角色信息对话框 -->
        <el-dialog
                title="编辑角色信息"
                :visible.sync="showEditDialogVisible"
                width="30%"
                >
                <el-form :model="editRolesForm" :rules="RolesRules" ref="editRolesRef"  label-width="180px">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="editRolesForm.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="editRolesForm.roleDesc"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="showEditDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editRoles">确 定</el-button>
                </span>
             </el-dialog>
        <!-- 分配权限对话框 -->
        <el-dialog
            title="分配权限"
            @close="setRightDialogClose"
            :visible.sync="showSetRightDialogVisible"
            width="30%"
            
            >
            <el-tree
            ref="treeRef"
                :data="rightList"
                show-checkbox
                node-key="id"
                :default-expand-all="true"
                :default-checked-keys="defKeys"
                :props="treeProps">
            </el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="alloRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        return {
           rolesList : [],
           showSetRightDialogVisible:false,
           showAddDialogVisible:false,
           showEditDialogVisible:false,
            //所有权限的数据
           rightList:[],
        //    树形控件的树形绑定对象
           treeProps:{
               label:'authName',
               children:'children'
           },
        //    默认选中的id值
           defKeys:[],
           roleId:'',
           RolesRules:{
               roleName:[
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    {
                        min: 2,
                        max: 10,
                        message: '分类名称的长度在 2 到 10 个字符',
                        trigger: 'blur',
                    },
               ]
           },
           addRolesForm:{
               id:'',
               roleName:'aaa',
               roleDesc:'aaa'
           },
           editRolesForm:{
               id:'',
               roleName:'',
               roleDesc:''
           },
        };
    },
    mounted(){
        this.getRolesList()
    },
    methods:{
        // 获取角色列表
        async getRolesList(){
            const {data:res} = await this.$http.get('/roles')
            if(res.meta.status !== 200) return this.$message.error('获取角色列表失败')
            this.rolesList = res.data
        },
        // 删除指定角色权限
        async removeRightById(role,rightId){
            const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
            }).catch(err => err)
            if(confirmResult !== 'confirm'){
                return this.$message.info('取消删除操作')
            }
            const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
            if(res.meta.status !== 200) {return this.$message.error('删除失败')}
            // 刷新数据
            role.children = res.data
        },
        // 通过递归形式获取角色下所有三级权限的id并保存到数组中
        getDefKeys(node,arr){
            // 如果当前节点不包含children属性，则为三级节点
            if(!node.children){
                return arr.push(node.id)
            }
            node.children.forEach(items => {
                this.getDefKeys(items,arr)
            });
        },
        // 展示分配权限的对话框
        async showSetRightDialog(role){
            // 获取所有权限列表
            const {data:res} = await this.$http.get('rights/tree')    
            if(res.meta.status !== 200) return this.$message.error('请求失败')
            this.roleId = role.id
            // 获取到的权限数据
            this.rightList = res.data
            // 递归获取三级节点的id
            this.getDefKeys(role,this.defKeys)
            
            this.showSetRightDialogVisible = true
        },
        setRightDialogClose(){
            this.defKeys=[]
        },
        // 分配权限
        async alloRights(){
            const keys=[
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const idStr = keys.join(',')
            const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
            console.log(res.data);
            if(res.meta.status !== 200) return this.$message.error('分配权限失败')
            this.$message.success('分配权限成功')
            this.getRolesList()
            this.showSetRightDialogVisible = false
        },
        // 添加角色对话框
        showAddDialog(){
            this.showAddDialogVisible = true
        },
        // 添加角色
        addRoles(){
            this.$refs.addRolesRef.validate(async valid=>{
                if(!valid) return
                const {data:res} = await this.$http.post('roles',this.addRolesForm)
                if(res.meta.status !== 201) return this.$message.error('添加失败')
                this.$message.success('添加成功')
                this.getRolesList()
                this.showAddDialogVisible = false
            })
        },
        // 编辑角色信息对话框
        async showEditDialog(id){
            this.showEditDialogVisible = true
            const {data:res} = await this.$http.get('roles/'+id) 
            if(res.meta.status !== 200) return this.$message.error('查询角色信息失败')
            this.editRolesForm = res.data
        },
        // 编辑角色信息
        editRoles(){
            this.$refs.editRolesRef.validate(async valid=>{
                if(!valid) return
                const {data:res} = await this.$http.put('roles/'+this.editRolesForm.roleId,this.editRolesForm)
                if(res.meta.status !== 200) return this.$message.error('修改失败')
                this.$message.success('修改成功')
                this.getRolesList()
                this.showEditDialogVisible = false
            })
        },
        // 删除角色
        async deleteRoles(id){
            const configResult = await this.$confirm(
                '此操作将永久删除该角色, 是否继续?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ) 
            if(configResult !== 'confirm') return this.$message.info('您已取消操作')
            const {data:res} = await this.$http.delete('roles/'+id)
            if(res.meta.status !== 200) return this.$message.error('删除失败')
            this.$message.success('删除成功')
            this.getRolesList()
        }
        
        
    }
}
</script>
<style lang="less">
    .el-table {
    margin-top: 15px;
    }
    .el-tag{
        margin: 7px;
    }
    .bdtop{
        border-top: 1px solid #eee;
    }
    .bdbottom{
        border-bottom: 1px solid #eee;
    }
    .vcenter{
        display: flex;
        align-items: center;
    }
</style>